package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.adm.impl;


import com.cqhilink.api.common.utils.UniqueUtil;
import com.google.common.collect.Maps;
import com.kingyun.gpsinspection.purificationservice.common.activiti.ActivitiConstants;
import com.kingyun.gpsinspection.purificationservice.common.enums.Annualenum;
import com.kingyun.gpsinspection.purificationservice.common.enums.LeaveEnum;
import com.kingyun.gpsinspection.purificationservice.common.utils.CommonUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.LeaveMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmOrganizationMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.Leave;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.LeaveHistoricProcessInstanceEntity;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.LeaveTaskEntity;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.OrgLevel;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.LeaveService;
import com.kingyun.gpsinspection.purificationservice.services.activitiservice.base.BaseWorkFlowServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 请假服务实现类
 *
 * @author zjh
 * @since 20170704
 */
public class LeaveServiceImpl extends BaseWorkFlowServiceImpl implements LeaveService {


    /**
     * 请假申请的流程KEY
     */
    private final String KEY = "leave";

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private JsmOrganizationMapper jsmOrganizationMapper;


    /**
     * 保存请假业务实体并发起审批
     *
     * @param leave      请假业务
     * @param employeeVo 当前登录人
     * @return
     */
    @Override
    public Map<String, Object> saveLeave(Leave leave, EmployeeVo employeeVo) throws Exception {
        Map<String, Object> variables = new HashMap<>();
        //保存业务数据
        String businessKey = UniqueUtil.uuid();
        leave.setId(businessKey);
        leave.setCreateUserId(employeeVo.getEmployeeId());
        leave.setModifyUserId(employeeVo.getEmployeeId());
        leave.setCreateTime(CommonUtil.getTimeString());
        leave.setModifyTime(CommonUtil.getTimeString());
        leaveMapper.insertSelective(leave);
        //根据人员的组织等级来判断他所走的流程
        if (leave.getFlowType() == 1) {
            //班组人员
            variables.put("cond", 1);
            String[] str = {leave.getFirstApproval()};
            variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
        } else if (leave.getFlowType() == 2) {
            //部门人员
            variables.put("cond", 2);
            String[] str = {leave.getSecondApproval()};
            variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
        } else if (leave.getFlowType() == 3) {
            //厂领导
            variables.put("cond", 3);
            String[] str = {leave.getThirdlyApproval()};
            variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
        }
        //发起流程
        Map<String, Object> result = super.startProcessInstanceByKey(KEY, businessKey, variables, employeeVo.getEmployeeId());
        return result;
    }

    /**
     * 得到年假的剩余天数
     *
     * @param employeeVo
     * @param year
     * @return
     */
    @Override
    public Integer queryMannualDays(String year, EmployeeVo employeeVo) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date applyTime = simpleDateFormat.parse(year);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(applyTime);
        Long workYear = getYear(applyTime, employeeVo.getCreateTime());
        if (workYear >= 1) {
            //获取我已经用过的天数
            int remainYear = leaveMapper.queryMannualDays(employeeVo.getEmployeeId(), calendar.get(Calendar.YEAR) + "");
            Annualenum[] values = Annualenum.values();
            int days = 0;
            //根据工作年限获取我应有的天数
            for (Annualenum annualenum : values) {
                if (workYear.intValue() == annualenum.getYear()) {
                    days = annualenum.getDays();
                    break;
                }
            }
            //获取我审批中的天数
            int runningTypeDays = leaveMapper.getRunningTypeDays(employeeVo.getEmployeeId(), LeaveEnum.ANNUAL.getCode());
            //计算出我剩余的天数
            days = (days - remainYear - runningTypeDays);
            return days;
        }
        return 0;
    }

    /**
     * 职工累计工作已满1年不满10年的，年休假5天；已满10年不满20年的，年休假10天；已满20年的，年休假15天。
     */
    private long getYear(Date applyTime, Date createTime) {
        long l = applyTime.getTime() - createTime.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long mon = day / 30;
        long year = mon / 12;
        if (year >= 1 && year < 10) {
            //1-10年
            return 1L;
        } else if (year >= 10 && year < 20) {
            //10-20年
            return 2L;
        } else if (year >= 20) {
            //大于20年
            return 3L;
        } else {
            //小于1年
            return 1L;
        }
    }

    /**
     * 得到请假实体
     *
     * @param id
     * @return
     */
    @Override
    public Leave queryLeaveById(String id) {
        return leaveMapper.selectByPrimaryKey(id);
    }

    /**
     * 某人发起的流程列表
     *
     * @param leaveHistoricProcessInstanceEntity
     * @return
     */
    @Override
    public Map<String, Object> getRunningProcessinstances(LeaveHistoricProcessInstanceEntity leaveHistoricProcessInstanceEntity) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("rows", leaveMapper.getRunningProcessinstances(leaveHistoricProcessInstanceEntity));
        result.put("total", leaveMapper.getRunningProcessinstancesCount(leaveHistoricProcessInstanceEntity));
        return result;
    }

    /**
     * 得到待办任务列表
     *
     * @param leaveTaskEntity
     * @return
     */
    @Override
    public Map<String, Object> getTodoTasks(LeaveTaskEntity leaveTaskEntity) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("rows", leaveMapper.getTodoTask(leaveTaskEntity));
        result.put("total", leaveMapper.getTodoTaskCount(leaveTaskEntity));
        return result;
    }

    /**
     * 驳回请求，重新填写
     *
     * @param leave    业务实体
     * @param taskId   任务ID
     * @param variable 流程变量
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<String, Object> reApply(Leave leave, String taskId, Map<String, Object> variable, String userId) {
        leaveMapper.updateByPrimaryKeySelective(leave);
        return super.completeTask(taskId, variable, null, userId);
    }

    /**
     * 根据当前人员的组织id查询组织层级信息，及其父级层级信息
     *
     * @param orgId
     */
    @Override
    public OrgLevel queryLevelInfoByOrgId(String orgId) {
        return jsmOrganizationMapper.getLevelInfoByOrgId(orgId);
    }


}
